package com.sk.weichat.ui.groupchat;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.sk.weichat.AppConfig;
import com.sk.weichat.AppConstant;
import com.sk.weichat.MyApplication;
import com.sk.weichat.R;
import com.sk.weichat.bean.Friend;
import com.sk.weichat.bean.OpenGroupInfoBean;
import com.sk.weichat.bean.RoomMember;
import com.sk.weichat.bean.SearchUserAndRoomBean;
import com.sk.weichat.bean.message.GroupMessage;
import com.sk.weichat.bean.message.MucRoom;
import com.sk.weichat.bean.message.MucRoomMember;
import com.sk.weichat.broadcast.MsgBroadcast;
import com.sk.weichat.broadcast.MucgroupUpdateUtil;
import com.sk.weichat.db.InternationalizationHelper;
import com.sk.weichat.db.dao.FriendDao;
import com.sk.weichat.db.dao.GroupMessageDao;
import com.sk.weichat.db.dao.RoomMemberDao;
import com.sk.weichat.helper.AvatarHelper;
import com.sk.weichat.helper.DialogHelper;
import com.sk.weichat.ui.base.BaseActivity;
import com.sk.weichat.ui.me.PersonalCenterActivity;
import com.sk.weichat.ui.message.MucChatActivity;
import com.sk.weichat.ui.message.multi.NoticeListActivity;
import com.sk.weichat.ui.message.multi.RoomInfoActivity;
import com.sk.weichat.ui.message.search.NetSearchRoomsActivity;
import com.sk.weichat.ui.message.search.SearchUserAndRoomActivity;
import com.sk.weichat.ui.other.QRcodeActivity;
import com.sk.weichat.util.AsyncUtils;
import com.sk.weichat.util.Constants;
import com.sk.weichat.util.PreferenceUtils;
import com.sk.weichat.util.ToastUtil;
import com.sk.weichat.view.SelectionFrame;
import com.xuan.xuanhttplibrary.okhttp.HttpUtils;
import com.xuan.xuanhttplibrary.okhttp.callback.BaseCallback;
import com.xuan.xuanhttplibrary.okhttp.result.ObjectResult;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import de.greenrobot.event.EventBus;
import okhttp3.Call;

import static com.sk.weichat.bean.message.MucRoom.Notice;
import static com.sk.weichat.ui.groupchat.RoomChangeContentActivity.NOTICE;

/**
 * @Author: chenzl
 * @ClassName: OpenGroupInfoActivity
 * @Description: 公开群信息
 * @CreateDate: 2019/9/12 18:04
 */
public class OpenGroupInfoActivity extends BaseActivity {

    private ImageView imgGroupAvatar;
    private TextView tvGroupName;
    private TextView tvGroupNumble;
    private TextView tvGroupManage;
    private GridView gridGroupManage;
    private TextView tvRoomDesc;
    private TextView tvNoticeContent;
    private TextView tvNotice;
    private RelativeLayout roomQrcode;
    private Button btnAddGroup;

    private String RoomId;
    private String RoomJid;
    private String packetId;
    private OpenGroupInfoBean mucRoom;

    private GridViewAdapter mAdapter;


    private List<MucRoomMember> members = new ArrayList<>();//管理员列表

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_open_group_info);
        getSupportActionBar().hide();

        initView();
        RoomId = getIntent().getStringExtra("RoomId");
//        RoomJid = getIntent().getStringExtra("RoomJid");
        packetId = getIntent().getStringExtra("packetId");
        loadMembers();
    }

    private void initView() {
        findViewById(R.id.iv_title_left).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        TextView tvTitle = findViewById(R.id.tv_title_center);
        tvTitle.setText(R.string.room_info);

        imgGroupAvatar = findViewById(R.id.img_group_avatar);
        tvGroupName = findViewById(R.id.tv_group_name);
        tvGroupNumble = findViewById(R.id.tv_group_numble);
        tvGroupManage = findViewById(R.id.tv_group_manage);
        gridGroupManage = findViewById(R.id.grid_group_manage);
        tvRoomDesc = findViewById(R.id.tv_room_desc);
        tvNoticeContent = findViewById(R.id.tv_notice_content);
        tvNotice = findViewById(R.id.tv_notice);
        roomQrcode = findViewById(R.id.room_qrcode);
        btnAddGroup = findViewById(R.id.btn_add_group);

        tvGroupManage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(mContext, GroupManageActivity.class);
                intent.putExtra("members", (Serializable) members);
                startActivity(intent);
            }
        });
        // 公告
        findViewById(R.id.notice_rl).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mucRoom != null) {
                    Intent intent = new Intent(OpenGroupInfoActivity.this, NoticeListActivity.class);
                    intent.putExtra("mRoomId", mucRoom.getId());
                    startActivity(intent);
                }
            }
        });

        // 二维码
        roomQrcode.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.e("lzs", "mucRoom.getTGroupHeads():" + mucRoom.getTGroupHeads());
                Intent intent = new Intent(OpenGroupInfoActivity.this, QRcodeActivity.class);
                intent.putExtra("isgroup", true);
                intent.putExtra("isopengroup", true);
                intent.putExtra("group_name", mucRoom.getName());
                intent.putExtra("group_image", mucRoom.getTGroupHeads());
                intent.putExtra("userid", mucRoom.getId());
                intent.putExtra("roomJid", mucRoom.getJid());
                intent.putExtra("packetId", packetId);
                startActivity(intent);
            }
        });
        btnAddGroup.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                startActivity(new Intent(OpenGroupInfoActivity.this, ApplyForAddGroupActivity.class));
                roomAutoJoin();
            }
        });
        mAdapter = new GridViewAdapter();
        gridGroupManage.setAdapter(mAdapter);
        gridGroupManage.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = new Intent(mContext, PersonalCenterActivity.class);
                intent.putExtra(AppConstant.EXTRA_USER_ID, members.get(position).getUserId());
                intent.putExtra(PersonalCenterActivity.KEY_FROM_ADD_TYPE, PersonalCenterActivity.FROM_ADD_TYPE_GROUP);
                mContext.startActivity(intent);
            }
        });

    }

    /**
     * @author: czl
     * @description 获取群组信息
     * @date: 2019/9/16 10:00
     */
    private void loadMembers() {
        HashMap<String, String> params = new HashMap<>();
        params.put("access_token", coreManager.getSelfStatus().accessToken);
        Log.e("lzs", "loadMembers:" + RoomId);
        params.put("roomId", RoomId);
        params.put("pageSize", Constants.MUC_MEMBER_PAGE_SIZE);

        HttpUtils.get().url(coreManager.getConfig().ROOM_GET)
                .params(params)
                .build()
                .execute(new BaseCallback<OpenGroupInfoBean>(OpenGroupInfoBean.class) {

                             @Override
                             public void onResponse(ObjectResult<OpenGroupInfoBean> result) {
                                 if (result.getResultCode() == 1 && result.getData() != null) {
                                     mucRoom = result.getData();
                                     if (mucRoom.getIsLook() == 0) {//公开群
                                         AvatarHelper.getInstance().displayUrl(coreManager.readConfigBean().getDownloadAvatarUrl() + mucRoom.getTGroupHeads(), imgGroupAvatar, R.drawable.groupdefault);
                                         btnAddGroup.setVisibility(View.VISIBLE);
                                     } else {
                                         if (!TextUtils.isEmpty(packetId)) {
                                             GroupMessage mGroupMessage = GroupMessageDao.getInstance().getGroupMessage(coreManager.getSelf().getUserId(), packetId);
                                             AvatarHelper.getInstance().displayAvatar(mGroupMessage.getOwnerId(), mGroupMessage, imgGroupAvatar);
                                         } else {
                                             Friend friend = FriendDao.getInstance().getFriend(coreManager.getSelf().getUserId(), mucRoom.getJid());
                                             if (friend != null) {
                                                 AvatarHelper.getInstance().displayGroupAvatar(coreManager.getSelf().getUserId(), friend, imgGroupAvatar);
                                             }
                                         }
                                         btnAddGroup.setVisibility(View.GONE);
                                     }

                                     tvGroupName.setText(mucRoom.getName());
                                     tvGroupNumble.setText(mucRoom.getUserSize() + "人");

                                     //获取群管理员
                                     for (int i = 0; i < mucRoom.getMembers().size(); i++) {
                                         if (mucRoom.getMembers().get(i).getRole() == 1 || mucRoom.getMembers().get(i).getRole() == 2) {
                                             members.add(mucRoom.getMembers().get(i));
                                         }
                                     }
                                     tvGroupManage.setText("共" + members.size() + "人");
                                     mAdapter.notifyDataSetChanged();
                                     if (!TextUtils.isEmpty(mucRoom.getDesc())) {
                                         tvRoomDesc.setVisibility(View.VISIBLE);
                                         tvRoomDesc.setText(mucRoom.getDesc());
                                     } else {
                                         tvRoomDesc.setVisibility(View.GONE);
                                     }
//                                     List<Notice> notices = mucRoom.getNotices();
                                     OpenGroupInfoBean.NoticeBean notices = mucRoom.getNotice();
                                     if (notices.getText() != null && !TextUtils.isEmpty(notices.getText())) {
                                         tvNoticeContent.setText(notices.getText());
                                         tvNoticeContent.setVisibility(View.VISIBLE);
                                         tvNotice.setVisibility(View.GONE);
                                     } else {
                                         tvNotice.setVisibility(View.VISIBLE);
                                         tvNotice.setText(InternationalizationHelper.getString("JX_NotAch"));
                                         tvNoticeContent.setVisibility(View.GONE);
                                     }

                                     MyApplication.getInstance().saveGroupPartStatus(mucRoom.getJid(), mucRoom.getShowRead(), mucRoom.getAllowSendCard(),
                                             mucRoom.getAllowConference(), mucRoom.getAllowSpeakCourse(), mucRoom.getTalkTime());
                                     PreferenceUtils.putBoolean(MyApplication.getContext(),
                                             Constants.IS_NEED_OWNER_ALLOW_NORMAL_INVITE_FRIEND + mucRoom.getJid(), mucRoom.getIsNeedVerify() == 1);
                                     PreferenceUtils.putBoolean(MyApplication.getContext(),
                                             Constants.IS_ALLOW_NORMAL_SEND_UPLOAD + mucRoom.getJid(), mucRoom.getAllowUploadFile() == 1);

                                     AsyncUtils.doAsync(this, (AsyncUtils.Function<AsyncUtils.AsyncContext<BaseCallback<OpenGroupInfoBean>>>) baseCallbackAsyncContext -> {
                                         for (int i = 0; i < mucRoom.getMembers().size(); i++) {// 在异步任务内存储
                                             RoomMember roomMember = new RoomMember();
                                             roomMember.setRoomId(mucRoom.getId());
                                             roomMember.setUserId(mucRoom.getMembers().get(i).getUserId());
                                             roomMember.setUserName(mucRoom.getMembers().get(i).getNickName());
                                             if (TextUtils.isEmpty(mucRoom.getMembers().get(i).getRemarkName())) {
                                                 roomMember.setCardName(mucRoom.getMembers().get(i).getNickName());
                                             } else {
                                                 roomMember.setCardName(mucRoom.getMembers().get(i).getRemarkName());
                                             }
                                             roomMember.setRole(mucRoom.getMembers().get(i).getRole());
                                             roomMember.setCreateTime(mucRoom.getMembers().get(i).getCreateTime());
                                             RoomMemberDao.getInstance().saveSingleRoomMember(mucRoom.getId(), roomMember);
                                         }
                                     });

//                                     saveMucLastRoamingTime(mLoginUserId, mucRoom.getId(), mucRoom.getMembers().get(mucRoom.getMembers().size() - 1).getCreateTime(), false);

                                     // 更新消息界面
                                     MsgBroadcast.broadcastMsgUiUpdate(OpenGroupInfoActivity.this);
                                     // 更新群聊界面
                                     MucgroupUpdateUtil.broadcastUpdateUi(OpenGroupInfoActivity.this);

                                 } else if (result.getResultCode() == 1040328) {//群聊已被解散
                                     SelectionFrame tipDialog = new SelectionFrame(OpenGroupInfoActivity.this, true);
                                     tipDialog.setCanceledOnTouchOutside(false);
                                     tipDialog.setSomething(getString(R.string.dialog_title), result.getResultMsg(), new SelectionFrame.OnSelectionFrameClickListener() {
                                         @Override
                                         public void cancelClick() {

                                         }

                                         @Override
                                         public void confirmClick() {
                                             finish();
                                         }
                                     });
                                     tipDialog.show();
                                 } else {
                                     ToastUtil.showToast(OpenGroupInfoActivity.this, result.getResultMsg());
                                 }
                             }

                             @Override
                             public void onError(Call call, Exception e) {
                                 ToastUtil.showErrorNet(OpenGroupInfoActivity.this);
                             }
                         }
                );
    }

    class GridViewAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            return members.size();
        }

        @Override
        public Object getItem(int position) {
            return members.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            if (convertView == null) {
                convertView = LayoutInflater.from(mContext).inflate(R.layout.item_room_info_view, parent, false);
                GridViewHolder vh = new GridViewHolder(convertView);
                convertView.setTag(vh);
            }
            GridViewHolder vh = (GridViewHolder) convertView.getTag();
            ImageView imageView = vh.imageView;
            TextView memberName = vh.memberName;
            imageView.setVisibility(View.VISIBLE);
            MucRoomMember mMucRoomMember = members.get(position);
            String name = TextUtils.isEmpty(mMucRoomMember.getRemarkName()) ? mMucRoomMember.getNickName() : mMucRoomMember.getRemarkName();
            AvatarHelper.getInstance().displayAvatar(name, mMucRoomMember.getUserId(), imageView, true);
            memberName.setText(name);
            return convertView;
        }
    }

    class GridViewHolder {
        ImageView imageView;
        TextView memberName;

        GridViewHolder(View itemView) {
            imageView = itemView.findViewById(R.id.content);
            memberName = itemView.findViewById(R.id.member_name);
        }
    }

    /**
     * @author: czl
     * @description 加群
     * @date: 2019/9/18 9:28
     */
    private void roomAutoJoin() {
        Map<String, String> params = new HashMap<>();
        params.put("access_token", coreManager.getSelfStatus().accessToken);
        params.put("roomId", mucRoom.getId());
        DialogHelper.showDefaulteMessageProgressDialog(OpenGroupInfoActivity.this);

        HttpUtils.post().url(coreManager.getConfig().ROOM_AUTO_JOIN)
                .params(params).build().execute(new BaseCallback<String>(String.class) {
            @Override
            public void onResponse(ObjectResult<String> result) {
                DialogHelper.dismissProgressDialog();
                if (result.getResultCode() == 1) {//加入成功 直接进群
                    EventBus.getDefault().post("cancle");//关闭页面
                    //进入群聊页面
                    Intent intent = new Intent(OpenGroupInfoActivity.this, MucChatActivity.class);
                    intent.putExtra(AppConstant.EXTRA_USER_ID, mucRoom.getJid());
                    intent.putExtra(AppConstant.EXTRA_NICK_NAME, mucRoom.getName());
                    intent.putExtra(AppConstant.EXTRA_IS_GROUP_CHAT, true);
                    startActivity(intent);
                    finish();
                } else if (result.getResultCode() == 1040320) {//群主开启了加群验证  跳转到发送加群申请页面
                    startActivity(new Intent(OpenGroupInfoActivity.this, ApplyForAddGroupActivity.class)
                            .putExtra("RoomId", mucRoom.getId()));

                } else if (result.getResultCode() == 1040319) {
                    ToastUtil.showToast(OpenGroupInfoActivity.this, result.getResultMsg());

                    Intent intent = new Intent(OpenGroupInfoActivity.this, MucChatActivity.class);
                    intent.putExtra(AppConstant.EXTRA_USER_ID, mucRoom.getJid());
                    intent.putExtra(AppConstant.EXTRA_NICK_NAME, mucRoom.getName());
                    intent.putExtra(AppConstant.EXTRA_IS_GROUP_CHAT, true);
                    startActivity(intent);
                    EventBus.getDefault().post("cancle");//关闭页面

                } else {
                    ToastUtil.showToast(OpenGroupInfoActivity.this, result.getResultMsg());
                }
            }

            @Override
            public void onError(Call call, Exception e) {
                DialogHelper.dismissProgressDialog();
                ToastUtil.showErrorNet(OpenGroupInfoActivity.this);
            }
        });
    }
}
